<template>
  <div
    class="structureMul block blockUser"
    :class="chooseResult.length > 0 && !dialogVisible ? 'structureMulNan' : ''"
  >
    <el-button type="text" @click="dialogVisible = true">+选择人员</el-button>

    <el-dialog
      title="选择人员"
      :visible.sync="dialogVisible"
      width="50%"
      :append-to-body="true"
      custom-class="topBlock"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="flexrow box">
        <div class="blockL">
          <div class="flexrow" style="justify-content: space-between">
            <span>您已选择：</span
            ><el-button
              type="info"
              v-if="chooseResult.length"
              @click="clearChooseresult"
              >清除所有</el-button
            >
          </div>
          <div class="flexrow chooseResultView">
            <div
              class="item"
              v-for="(item, index) in chooseResult"
              :key="index"
            >
              <el-tag closable type="info" @close="clearChoose(index)">
                {{ item.realname }}
              </el-tag>
            </div>
          </div>
        </div>
        <div class="blockR" v-loading="loading">
          <el-tree
            :data="dataTree"
            show-checkbox
            node-key="id"
            ref="tree"
            highlight-current
            :props="defaultProps"
            @node-click="handleNode"
            @check="handleCheck"
            @check-change="handleCheckChange"
          >
          </el-tree>
        </div>
        <div class="blockRR">
          <div class="blockRR-search flexrow">
            <div style="width: 70%">
              <el-input
                placeholder="请输入内容搜索"
                v-model="searchName"
                clearable
              >
              </el-input>
            </div>
            <el-button
              style="height: 34px"
              @click="
                deptId = '';
                page = 1;
                total = 2;
                getMember();
              "
              >搜索</el-button
            >
          </div>
          <div class="bolckRR-block" v-loading="userLoading" ref="userView">
            <!-- @scroll="userScroll()" -->
            <div
              class="userRr"
              v-for="(item, index) in userList"
              :key="index"
              @click="optinObj(index)"
            >
              <div class="userRr-choose" v-if="item.checked"></div>
              <img :src="item.img||'/static/img/headImg.png'" alt="" />
              <span>{{ item.realname }}</span>
            </div>
            <p
              v-if="userList.length < 1"
              style="
                text-align: center;
                color: #999;
                width: 100%;
                margin-top: 80px;
              "
            >
              暂无可选数据~
            </p>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="doneChoose">确 定</el-button>
      </span>
    </el-dialog>
    <div
      class="flexrow block_reshow"
      v-if="chooseResult && chooseResult.length > 0"
    >
      <div style="max-width: 98%; overflow: hidden; display: flex">
        <span
          style="
            font-size: 12px;
            margin-right: 10px;
            display: block;
            white-space: nowrap;
            color: #d9ecfe;
          "
          v-for="(item, index) in chooseResult"
          :key="index"
          >{{ item.realname }}</span
        >
      </div>
      <i
        class="el-icon-circle-close"
        style="margin-left: 10px"
        @click="delChoose()"
      ></i>
    </div>
  </div>
</template>
<script type="text/javascript">
import { depListAPI, userListAPI } from "@/api/common";
import ArrayMixin from "./ArrayMixin";

export default {
  name: "XhStrucUserCellMul", // 新建 struc-user-cell-mul
  components: {},
  mixins: [ArrayMixin],
  props: {
    /** 包含数据源 */
    item: Object,
    curVal: Array
  },
  data() {
    return {
      searchName: "", //搜索条件
      dialogVisible: false, // 展示popover
      defaultProps: {
        children: "children",
        label: "label",
      },
      dataTree: [],
      loading: false,
      chooseResult: [],
      page: 1, //当前页码
      limit: 10000, //一页总量,
      total: 2, //总页码
      userList: [],
      userLoading: false,
      userChoose: false, //处理全选
      deptId: null,
      chooseResult_dept: [], //部门选择结果
    };
  },
  computed: {},
  watch: {
    curVal(val){
      this.initCur()
    }
  },
  created() {
    this.getTree();
  },
  mounted() {
    this.initCur()
  },
  methods: {
    initCur(){
      if(this.curVal&&this.curVal.length>0){
        this.chooseResult = this.curVal;
      }
    },
    optinObj(index) {
      const obj = this.userList[index];
      if (obj.checked) {
        const i = this.chooseResult
          .map((item) => item.userId)
          .indexOf(obj.userId);
        // console.log("iiii", i);
        this.clearChoose(i);
      } else {
        this.chooseResult.push(obj);

        const i = this.chooseResult_dept
          .map((item) => item.deptId)
          .indexOf(obj.deptId);
        // console.log("i", i);
        // if (i < 0) {
        //   console.log(obj.deptId);
        //   const key_arr = this.$refs.tree.getCheckedKeys();
        //   console.log(key_arr,'key_arr')
        //   key_arr.push(obj.deptId);
        //   console.log(key_arr,'key_arr.push')
        //   this.$refs.tree.setCheckedKeys(key_arr);
        // }

        this.$set(this.userList[index], "checked", !obj.checked);
      }
      // console.log("checked", !obj.checked);
    },
    userScroll(e) {
      //分页加载下一页人员数据
      const scroll = this.$refs.userView.scrollTop; //滚动高度
      const sH = this.$refs.userView.scrollHeight;
      const h = this.$refs.userView.clientHeight;
      if (sH - scroll - h < 50 && !this.userLoading) this.getMember();
    },
    //获取人员列表
    getMember() {
      const page = this.page;
      const total = this.total;
      if (page > total) return;
      this.userLoading = true;
      let params = {
        page: page,
        pageType: 0,
        limit: this.limit,
        realname: this.searchName,
        label: 0,
        // status: 1,
      };
      if (this.deptId) {
        //部门选择器
        delete params.label;
        params.deptId = this.deptId;
      }
      // console.log("人员参数", params);
      userListAPI(params)
        .then((res) => {
          this.userLoading = false;
          // console.log("res", res);
          if (res.code == "0") {
            let _arr = [];
            _arr = res.data.list;
            if (this.searchName) this.searchName = "";
            if (
              this.userChoose ||
              this.chooseResult_dept.length > 0 ||
              this.chooseResult.length > 0
            ) {
              _arr = this.handleChoose(_arr, this.userChoose);
              // console.log(_arr, "handle_arr");
              this.userChoose = false;
            }
            if (this.page == 1) {
              this.userList = _arr;
              this.$refs.userView.scrollTop = 0;
            } else this.userList = this.userList.concat(_arr);
            this.total = res.data.totalPage;
            this.page += 1;
          }
        })
        .catch(() => {
          this.userLoading = false;
        });
    },
    clearChooseresult() {
      this.$refs.tree.setCheckedKeys([]);
      this.chooseResult = [];
      this.chooseResult_dept = [];
      const arr = this.userList.map((item) => {
        item.checked = false;
        return item;
      });

      this.userList = arr;
    },
    //处理全选
    handleChoose(arr, status) {
      let choose_arr = this.chooseResult;
      for (let i = 0; i < arr.length; i++) {
        // if (this.deptId != arr[i].deptId) return;
        arr[i].checked = status;
        if (choose_arr.length > 0) {
          const useridArr = choose_arr.map((item) => item.userId);
          const idx = useridArr.indexOf(arr[i].userId);
          // console.log(
          //   "status",
          //   this.chooseResult_dept.indexOf(arr[i].deptId),
          //   this.chooseResult_dept,
          //   arr[i].deptId
          // );
          if (idx < 0 && status) {
            choose_arr.push(arr[i]);
          } else {
            arr[i].checked =
              this.chooseResult_dept
                .map((item) => item.deptId)
                .indexOf(arr[i].deptId) > -1;
          }
          if (
            this.chooseResult_dept.length < 1 &&
            this.chooseResult.length > 0 &&
            idx > -1
          )
            arr[i].checked = true;
        } else choose_arr.push(arr[i]);
      }
      // console.log(choose_arr, "choose_arr");
      this.chooseResult = choose_arr;
      return arr;
    },

    //初始化人员列表回显
    initUserlist(deptId) {
      this.deptId = deptId;
      this.page = 1;
      this.total = 2;
      this.getMember();
    },
    //点击部门触发
    handleNode(obj, objNode, objCom) {
      if (obj.deptId == this.deptId) return;
      this.initUserlist(obj.deptId);
    },
    //选中触发
    handleCheck(checkedNodes, checkedKeys) {
      // console.log("checkedKeys", checkedKeys);
      const nodes = checkedKeys.checkedNodes;
      for (let i = 0; i < nodes.length; i++) {
        this.$refs.tree.store.nodesMap[nodes[i].id].expanded = true;
      }

      checkedNodes.unfold = true;
      if (
        checkedKeys.checkedKeys.length > 0 &&
        checkedKeys.checkedKeys.indexOf(checkedNodes.deptId) > -1
      ) {
        //选中
        this.userChoose = true;
        this.initUserlist(checkedNodes.deptId);
      }
      this.chooseResult_dept = this.$refs.tree.getCheckedNodes();
    },
    handleCheckChange(data, bool, boolstatus) {
      // return;
      if (!bool && this.chooseResult.length > 0) {
        this.chooseResult = this.chooseResult.filter(
          (item) => item.deptId != data.deptId
        );
        const userList = this.userList.filter(
          (item) => item.deptId == data.deptId
        );
        userList.map((item) => (item.checked = false));
        const _user = this.userList.filter(
          (item) => item.deptId != data.deptId
        );
        this.userList = [..._user, ...userList];

        // console.log(userList, "userList");
      }
    },
    //渲染树形组件
    getTree() {
      this.loading = true;
      let params = {
        type: "new_tree",
      };
      depListAPI(params)
        .then((res) => {
          const allList = res.data;
          this.dataTree = allList;
          if(allList.length>0) this.getMember();
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    //结果反推
    clearChoose(idx) {
      const deptID = this.chooseResult[idx].deptId;
      const userID = this.chooseResult[idx].userId;
      this.chooseResult.splice(idx, 1);
      // console.log("this.chooseResult", this.chooseResult);
      const userList_index = this.userList
        .map((item) => item.userId)
        .indexOf(userID);
      this.$set(this.userList[userList_index], "checked", false);
      if (this.chooseResult.length < 1) {
        // console.log("负责人清除完清除部门");
        //负责人清除完清除部门
        this.chooseResult_dept = [];
        this.$refs.tree.setCheckedNodes(this.chooseResult_dept);
        return;
      }

      const user_dept = this.chooseResult.map((item) => item.deptId);
      const user_deptIndex = user_dept.indexOf(deptID);

      if (user_deptIndex < 0) {
        // console.log(user_deptIndex, "user_deptIndex");
        //需要清除部门
        const deptArr = this.chooseResult_dept.map((item) => item.deptId);
        const deptArr_index = deptArr.indexOf(deptID);
        this.chooseResult_dept.splice(deptArr_index, 1);
        this.$refs.tree.setCheckedNodes(this.chooseResult_dept);
      }
    },
    //点击确定
    doneChoose() {
      this.dialogVisible = false;
      // console.log("valuec");
      this.$emit("valueChange", {
        value: this.chooseResult.map((item) => item.userId),
        valueContent: this.chooseResult,
        item: this.item,
      });
    },
    //清空选中
    delChoose() {
      this.chooseResult = [];
      this.chooseResult_dept = [];
      if (this.$refs.tree)
        this.$refs.tree.setCheckedNodes(this.chooseResult_dept);
      this.deptId = null;
      this.userList = [];
      this.$emit("valueChange", {
        value: [],
        valueContent: [],
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.block {
  position: relative;
  .block_reshow {
    position: absolute;
    width: 85vw;
    align-items: center;
    background: #4482ff;
    padding: 12px 0 12px 5px;
    margin-top: 10px;
    border-radius: 4px;
    left: -5vw;
  }
}
/deep/.topBlock {
  z-index: 9999;
}
.box {
  padding: 20px;
  height: 500px;
}
.flexrow {
  display: flex;
  flex-direction: row;
  align-items: normal !important;
}
.blockL {
  width: 30%;
  padding-right: 20px;
  border-right: 1px solid #eee;
  overflow-y: scroll;
}
.blockR {
  width: 38%;
  overflow-y: scroll;
}
.blockRR {
  width: 32%;
  .blockRR-search {
    top: 0;
    width: 100%;
    height: 45px;
    justify-content: space-around;
  }
  .bolckRR-block {
    height: 100%;
    overflow-y: scroll;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
  }
}
.userRr {
  position: relative;
  width: 60px;
  height: 80px;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 0 8px 15px 0;
  img {
    width: 30px;
    height: 30px;
    border-radius: 15px;
    margin-bottom: 6px;
  }
  span {
    font-size: 14px;
  }
  .userRr-choose {
    position: absolute;
    width: 14px;
    height: 14px;
    border-radius: 7px;
    top: 20px;
    background: url("/static/img/choose.svg");
    background-size: 100% 100%;
    left: calc((100% - 14px) / 2);
  }
}
.chooseResultView {
  flex-wrap: wrap;
  .item {
    margin: 10px 10px 0 0;
  }
}
</style>
